package cn.dzhang.rcp.hyperbola.dialogs;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.IProduct;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.equinox.security.storage.ISecurePreferences;
import org.eclipse.equinox.security.storage.SecurePreferencesFactory;
import org.eclipse.equinox.security.storage.StorageException;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.branding.IProductConstants;

import cn.dzhang.rcp.hyperbola.Activator;
import cn.dzhang.rcp.hyperbola.common.GlobalEnv;
import cn.dzhang.rcp.hyperbola.common.UIUtils;
import cn.dzhang.rcp.hyperbola.preferences.GeneralPreferencePage;
import cn.dzhang.rcp.hyperbola.service.UserService;

public class LoginDialog extends TitleAreaDialog {
	private static final GlobalEnv env = GlobalEnv.getInstance();
	private static final String AUTHENTICATED_USERNAMES = "authenticated usernames";
	private static final String LAST_LOGIN_USERNAME = "last login username";

	private Combo cmbUsername;
	private Text txtPassword;
	private Button btnRemeberPassword;
	private Button btnAutoLogin;

	/**
	 * Create the dialog.
	 * 
	 * @param parentShell
	 */
	public LoginDialog(Shell parentShell) {
		super(parentShell);
	}

	/**
	 * Create contents of the dialog.
	 * 
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		setMessage("Welcome to Login iSwitchView System");
		setTitle("Nanjing Postel");
		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);
		GridLayout gl_container = new GridLayout(2, false);
		gl_container.verticalSpacing = 15;
		container.setLayout(gl_container);
		GridData gd_container = new GridData(GridData.FILL_BOTH);
		gd_container.horizontalAlignment = SWT.CENTER;
		gd_container.verticalAlignment = SWT.CENTER;
		container.setLayoutData(gd_container);

		Label lblUsername = new Label(container, SWT.NONE);
		lblUsername.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		lblUsername.setText("Username:");

		cmbUsername = new Combo(container, SWT.BORDER);
		GridData gd_txtUsername = new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1);
		gd_txtUsername.widthHint = 250;
		cmbUsername.setLayoutData(gd_txtUsername);
		// txtUsername.getCombo().setLayoutData(gd_cmbvwUsername);
		// txtUsername.setLabelProvider(new UserViewerLabelProvider());
		// txtUsername.setContentProvider(new UserContentProvider());

		Label lblPassword = new Label(container, SWT.NONE);
		lblPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		lblPassword.setText("Password:");

		txtPassword = new Text(container, SWT.BORDER | SWT.PASSWORD);
		txtPassword.setText("password");
		txtPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));

		Label lblServer = new Label(container, SWT.NONE);
		lblServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));
		lblServer.setText("Server:");

		ComboViewer cmbvwServer = new ComboViewer(container, SWT.NONE);
		Combo cmbServer = cmbvwServer.getCombo();
		cmbServer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));

		Composite composite = new Composite(container, SWT.NONE);
		composite.setLayout(new GridLayout(2, false));
		composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				2, 1));

		btnRemeberPassword = new Button(composite, SWT.CHECK);
		btnRemeberPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				true, false, 1, 1));
		btnRemeberPassword.setText("Remeber Password");

		btnAutoLogin = new Button(composite, SWT.CHECK);
		btnAutoLogin.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (btnAutoLogin.getSelection()) {
					btnRemeberPassword.setSelection(true);
				}
			}
		});
		btnAutoLogin.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));
		btnAutoLogin.setText("Auto Login");

		setup();

		return area;
	}

	private void setup() {
		IEclipsePreferences pref = ConfigurationScope.INSTANCE
				.getNode(Activator.PLUGIN_ID);
		String username = pref.get(LAST_LOGIN_USERNAME, "");
		String[] usernames = pref.get(AUTHENTICATED_USERNAMES, "").split(",");

		cmbUsername.setItems(usernames);
		cmbUsername.setText(username);

		ISecurePreferences securePref = SecurePreferencesFactory.getDefault();

		btnAutoLogin.setSelection(pref.getBoolean(
				GeneralPreferencePage.AUTO_LOGIN, false));

		try {
			String password = securePref.get(username, "");
			txtPassword.setText(password);
		} catch (StorageException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("iSwitchView Login");
		IProduct product = Platform.getProduct();
		String imageUrlString = product
				.getProperty(IProductConstants.WINDOW_IMAGES);
		String[] imageUrls = StringUtils.split(imageUrlString, ',');

		Image[] images = new Image[imageUrls.length];

		for (int i = 0; i < images.length; i++) {
			images[i] = UIUtils.getImage(imageUrls[i]);
		}
		newShell.setImages(images);
		// UIUtils.setDefaultBackgroundColor(newShell);
	}

	@Override
	protected void okPressed() {
		onLogin();
		super.okPressed();
	}

	private void onLogin() {
		env.refresh();

		UserService userService = env.getBean(UserService.class);
		System.err.println(userService);

		IScopeContext ctx = ConfigurationScope.INSTANCE;
		IEclipsePreferences pref = ctx.getNode(Activator.PLUGIN_ID);

		String _usernames = pref.get(AUTHENTICATED_USERNAMES, "");
		String[] usernames = _usernames.split(",");

		String username = cmbUsername.getText().trim();
		if (!ArrayUtils.contains(usernames, username)) {
			if (StringUtils.isBlank(_usernames)) {
				pref.put(AUTHENTICATED_USERNAMES, username);
			} else {
				pref.put(AUTHENTICATED_USERNAMES,
						String.format("%s,%s", _usernames, username));
			}
		}

		pref.put(LAST_LOGIN_USERNAME, cmbUsername.getText());

		pref.putBoolean(GeneralPreferencePage.AUTO_LOGIN,
				btnAutoLogin.getSelection());

		String password = txtPassword.getText().trim();
		if (!btnRemeberPassword.getSelection()) {
			password = "";
		}

		ISecurePreferences securePrefs = SecurePreferencesFactory.getDefault();
		try {
			securePrefs.put(username, password, true);
		} catch (StorageException e) {
			e.printStackTrace();
		}

		try {
			pref.flush();
			securePrefs.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * Create contents of the button bar.
	 * 
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
				true);
		createButton(parent, IDialogConstants.CANCEL_ID,
				IDialogConstants.CANCEL_LABEL, false);
	}

	/**
	 * Return the initial size of the dialog.
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(500, 350);
	}

}
